package com.allwees.bs.c.module.ops.service.impl;

import com.allwees.bs.c.module.ops.entity.CouponDefEntity;
import com.allwees.bs.c.module.ops.repository.CouponDefRepository;
import com.allwees.bs.c.module.ops.service.CouponService;
import com.allwees.bs.c.module.user.dao.UserPointDao;
import com.allwees.bs.c.module.user.entity.UserPointEntity;
import com.allwees.bs.core.model.coupon.constant.ECouponUseType;
import com.allwees.core.common.util.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class CouponDefServiceImpl implements CouponService {

    @Autowired
    private CouponDefRepository couponRepository;

    @Resource
    private UserPointDao userPointDao;

    @Override
    public CouponDefEntity getByUuid(String couponUuid) {
        return couponRepository.getByUuid(couponUuid);
    }

    @Override
    public List<CouponDefEntity> findExchangeCoupons(String userUuid) {
        UserPointEntity userPoint = userPointDao.findOneByField("user_uuid",userUuid);

        List<CouponDefEntity> exchangeCoupons = couponRepository.findByUseTypes(ECouponUseType.pointExchanges().toArray(new ECouponUseType[0]));

        for (CouponDefEntity coupon : exchangeCoupons) {
            if(coupon.getPointDeductAmt() != null){
                coupon.setPointExchange(coupon.getPointDeductAmt().compareTo(userPoint.getValue()) <= 0);
            }
        }
        return exchangeCoupons;
    }

    @Override
    public BigDecimal findSignInMinDeductAmt() {
        List<CouponDefEntity> exchangeCoupons = couponRepository.findByUseTypes(ECouponUseType.pointExchanges().toArray(new ECouponUseType[0]));
        BigDecimal minDeductAmt = null;
        for (CouponDefEntity coupon : exchangeCoupons) {
            minDeductAmt = MoneyUtil.min(minDeductAmt, coupon.getMaxDeductAmt());
        }
        return minDeductAmt;
    }
}
